using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Wintellect.Touch
{
    public class TouchableComboBox : ComboBox
    {
        /// <summary>
        /// Builds the visual tree for the <see cref="T:System.Windows.Controls.ComboBox"/> when a new template is applied.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            // Locate the ScrollViewer item in the template and attach the scrolling manipulation behavior
            var scrollViewer = GetTemplateChild("ScrollViewer");

            // Find an associated manipulation behavior if one exists.  If not, create one and attach it.
            var behaviors = Interaction.GetBehaviors(scrollViewer);
            var touchScrollBehavior = behaviors.OfType<ScrollViewerTouchScrollBehavior>().FirstOrDefault();
            if (touchScrollBehavior == null)
            {
                touchScrollBehavior = new ScrollViewerTouchScrollBehavior();

                // Defer the attach operation so it doesn't happen within this Attach, or an exception is raised.
                scrollViewer.Dispatcher.BeginInvoke(() => behaviors.Add(touchScrollBehavior));
            }

            // When the list selection is changed, close the drop down if it is open.  The default button click behavior is being omitted to support touch.
            SelectionChanged += (o, e) =>
            {
                if (IsDropDownOpen) IsDropDownOpen = false;
            };
        }

        /// <summary>
        /// Retrieves an empty combo box item.
        /// </summary>
        /// <returns>An empty combo box item.</returns>
        protected override DependencyObject GetContainerForItemOverride()
        {
            // Instead of returning a ComboBoxItem, return a specialized TouchableComboBoxItem
            return new TouchableComboBoxItem();
        }
    }
}